'use client'

import React, { useState, useMemo, useCallback, memo } from 'react'
import { Card, Table, Button, Input, Select, Form, Modal, Space, message, Popconfirm } from 'antd'
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons'

interface User {
  id: number
  username: string
  email: string
  phone: string
  department: string
  role: string
  status: string
  createTime: string
}

// 使用 memo 优化组件，避免不必要的重渲染
const UsersPage = memo(function UsersPage() {
  const [users, setUsers] = useState<User[]>([
    { id: 1, username: '张三', email: 'zhangsan@example.com', phone: '13800138001', department: '技术部', role: '管理员', status: '启用', createTime: '2024-01-15 10:00:00' },
    { id: 2, username: '李四', email: 'lisi@example.com', phone: '13800138002', department: '人事部', role: '普通用户', status: '启用', createTime: '2024-01-15 10:00:00' },
    { id: 3, username: '王五', email: 'wangwu@example.com', phone: '13800138003', department: '财务部', role: '部门经理', status: '启用', createTime: '2024-01-15 10:00:00' },
    { id: 4, username: '赵六', email: 'zhaoliu@example.com', phone: '13800138004', department: '技术部', role: '普通用户', status: '禁用', createTime: '2024-01-15 10:00:00' },
  ])
  const [filteredUsers, setFilteredUsers] = useState<User[]>(users)
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [editingUser, setEditingUser] = useState<User | null>(null)
  const [searchForm] = Form.useForm()
  const [form] = Form.useForm()

  // 使用 useMemo 优化选项数据
  const departmentOptions = useMemo(() => ['技术部', '人事部', '财务部', '市场部', '运营部'], [])
  const statusOptions = useMemo(() => ['启用', '禁用'], [])

  // 使用 useMemo 优化列定义
  const columns = useMemo(() => [
    { title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
    { title: '用户名', dataIndex: 'username', key: 'username' },
    { title: '邮箱', dataIndex: 'email', key: 'email' },
    { title: '手机号', dataIndex: 'phone', key: 'phone' },
    { title: '部门', dataIndex: 'department', key: 'department' },
    { title: '角色', dataIndex: 'role', key: 'role' },
    { title: '状态', dataIndex: 'status', key: 'status' },
    { title: '创建时间', dataIndex: 'createTime', key: 'createTime' },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_: any, record: User) => (
        <Space>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定删除这个用户吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              danger
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ], [])

  // 查询栏筛选逻辑 - 使用 useCallback 优化
  const handleSearch = useCallback((values: any) => {
    let data = [...users]
    if (values.username) {
      data = data.filter(u => u.username.includes(values.username))
    }
    if (values.department) {
      data = data.filter(u => u.department === values.department)
    }
    if (values.status) {
      data = data.filter(u => u.status === values.status)
    }
    setFilteredUsers(data)
  }, [users])

  const handleReset = useCallback(() => {
    searchForm.resetFields()
    setFilteredUsers(users)
  }, [searchForm, users])

  const handleAdd = useCallback(() => {
    setEditingUser(null)
    form.resetFields()
    setIsModalVisible(true)
  }, [form])

  const handleEdit = useCallback((user: User) => {
    setEditingUser(user)
    form.setFieldsValue(user)
    setIsModalVisible(true)
  }, [form])

  const handleDelete = useCallback((id: number) => {
    setUsers(users.filter(user => user.id !== id))
    setFilteredUsers(filteredUsers.filter(user => user.id !== id))
    message.success('删除成功')
  }, [users, filteredUsers])

  const handleModalOk = useCallback(() => {
    form.validateFields().then((values: any) => {
      if (editingUser) {
        setUsers(users.map(user =>
          user.id === editingUser.id ? { ...user, ...values } : user
        ))
        setFilteredUsers(filteredUsers.map(user =>
          user.id === editingUser.id ? { ...user, ...values } : user
        ))
        message.success('更新成功')
      } else {
        const newUser: User = {
          id: Math.max(...users.map(u => u.id)) + 1,
          ...values,
          createTime: new Date().toLocaleString()
        }
        setUsers([...users, newUser])
        setFilteredUsers([...filteredUsers, newUser])
        message.success('创建成功')
      }
      setIsModalVisible(false)
      form.resetFields()
    })
  }, [editingUser, users, filteredUsers, form])

  return (
    <div style={{ padding: 16, display: 'flex', flexDirection: 'column' }}>
      {/* 查询条件卡片 */}
      <Card style={{ marginBottom: 16 }}>
        <Form
          form={searchForm}
          layout="inline"
          onFinish={handleSearch}
        >
          <Form.Item name="username" label="用户名">
            <Input placeholder="请输入用户名" allowClear style={{ width: 160 }} />
          </Form.Item>
          <Form.Item name="department" label="部门">
            <Select placeholder="全部" allowClear style={{ width: 140 }}>
              {departmentOptions.map(dep => (
                <Select.Option key={dep} value={dep}>{dep}</Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="status" label="状态">
            <Select placeholder="全部" allowClear style={{ width: 120 }}>
              {statusOptions.map(st => (
                <Select.Option key={st} value={st}>{st}</Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">查询</Button>
          </Form.Item>
          <Form.Item>
            <Button onClick={handleReset}>重置</Button>
          </Form.Item>
        </Form>
      </Card>

      {/* 表格内容卡片 */}
      <Card 
        style={{ height: 600, minHeight: 0 }} 
        styles={{ body: { padding: '12px 24px' } }}
      >
        <div style={{ marginBottom: 8, display: 'flex', justifyContent: 'flex-end' }}>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleAdd}
          >
            新增用户
          </Button>
        </div>
        <Table
          columns={columns}
          dataSource={filteredUsers}
          rowKey="id"
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
          }}
        />
      </Card>

      <Modal
        title={editingUser ? '编辑用户' : '新增用户'}
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={() => setIsModalVisible(false)}
        width={600}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>
          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入正确的邮箱格式' }
            ]}
          >
            <Input placeholder="请输入邮箱" />
          </Form.Item>
          <Form.Item
            name="phone"
            label="手机号"
            rules={[{ required: true, message: '请输入手机号' }]}
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>
          <Form.Item
            name="department"
            label="部门"
            rules={[{ required: true, message: '请选择部门' }]}
          >
            <Select placeholder="请选择部门">
              {departmentOptions.map(dep => (
                <Select.Option key={dep} value={dep}>{dep}</Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="role"
            label="角色"
            rules={[{ required: true, message: '请选择角色' }]}
          >
            <Select placeholder="请选择角色">
              <Select.Option value="管理员">管理员</Select.Option>
              <Select.Option value="普通用户">普通用户</Select.Option>
              <Select.Option value="部门经理">部门经理</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select placeholder="请选择状态">
              <Select.Option value="启用">启用</Select.Option>
              <Select.Option value="禁用">禁用</Select.Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
})

export default UsersPage 